<?php

namespace App\Http\Controllers\admin;
use App\Cate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use MyFlash;
use App\Http\Requests\CreateCateRequest;
use App\Http\Requests\UpdateCateRequest;
class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cates =Cate::getCates();
        return view('admin.cate.lists')->with('cates',$cates);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cates =Cate::getCates();
        return view('admin.cate.create')->with('cates',$cates);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreateCateRequest $request)
    {
        $cate = new Cate;
        $cate->pid = $request->pid;
        $cate->name = $request->name;
        $cate->sort = $request->sort;
        if($cate->save()){
            MyFlash::success('分类添加成功');
            return redirect()->route('admin.cate.index');
        }else{
            MyFlash::error('分类添加失败');
            return back();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $cates =Cate::getCates();
        $res=Cate::find($id);
        return view('admin.cate.edit',compact('cates','res'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateCateRequest $request,$id)
    {
        $cate=Cate::findOrfail($id);
        $cate->name=$request->name;
        $cate->sort=$request->sort;
        $cate->pid =$request->pid;
        if($cate->save()){
            MyFlash::success('分类编辑成功');
            return redirect()->route('admin.cate.index');
        }else{
            MyFlash::error('分类编辑失败');
            return back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Cate::destroy(Cate::getCateIds($id))){
            MyFlash::success('分类删除成功');
            return redirect()->route('admin.cate.index');
        }else{
            MyFlash::error('分类删除失败');
            return back();
        }
    }
}
